/*package cn.huiyunche.service.base.interfaces.impl;

import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.google.common.collect.Maps;
import com.pingplusplus.Pingpp;
import com.pingplusplus.model.Event;
import com.pingplusplus.model.Transfer;
import com.pingplusplus.model.Webhooks;

import PayTransferService;

@Service

public class PayTransferServiceImpl implements PayTransferService {

    private static final Logger log = LoggerFactory.getLogger(PayTransferServiceImpl.class);
    
    private static final long CURRENTTIME = System.currentTimeMillis();
    
    Date currentTime = new Date();
    
    @Autowired
    private PayTransferDetailMapper payTransferDetailMapper = null;
    
    @Autowired
    private AccntDetailService accntDetailService = null;
    
    @Autowired
    private UserService UserService = null;
	
	@Override
	public Result<Object> accTransferBywx(BigDecimal amount, String openid) {
		log.info("提现申请Service,接收参数:openid:{}, amount:{}.", openid, amount);
		Result<Object> result = new Result<Object>(false);
		try {
			Pingpp.apiKey = StanUtils.getConstantPropertiesLoader().getProperty(PingPPConstant.PINGPP_API_AECRET_KEY);
			
			Map<String, Object> transfer = new HashMap<String, Object>();
			
			transfer.put("order_no", CURRENTTIME);
			transfer.put("currency", "cny");
			transfer.put("type",  "b2c");
			transfer.put("channel",  "wx");
			transfer.put("description", "Accounts Transfer");
			
			if(amount.compareTo(new BigDecimal(1)) == -1 || amount.compareTo(new BigDecimal(20000)) == 1){
				log.info("提现金额须在1-2W元之间.");
				result.setMessage("提现金额须在1-2W元之间.");
				result.setSuccess(false);
				return result;
			}
			if(StringUtils.isEmpty(openid)){
				log.info("提现用户标识为空.");
				result.setMessage("提现用户标识为空.");
				result.setSuccess(false);
				return result;
			}
			transfer.put("amount", amount.multiply(new BigDecimal(100)));
			transfer.put("recipient", openid);
			
			Map<String, String> app = new HashMap<String, String>();
			String appId = StanUtils.getConstantPropertiesLoader().getProperty(PingPPConstant.PINGPP_KEY);
			app.put("id", appId);
			transfer.put("app", app);
			Transfer resultTransfer = Transfer.create(transfer);
			if("failed".equalsIgnoreCase(resultTransfer.getStatus())){
				transfer.put("channel",  "wx_pub");
				resultTransfer = Transfer.create(transfer);
			}
			log.info("提现申请已经提交.Transfer:{}.", resultTransfer);
			
			// 提现信息初始化
			this.addPayTransferDetail(resultTransfer);
			
			result.setMessage("提现申请已经提交.");
			result.setSuccess(true);
			
		} catch (Exception e) {
			log.info("提现申请系统异常.", e);
			result.setMessage("用户提现系统异常.");
			result.setSuccess(false);
			e.printStackTrace();
		}
		
		return result;
	}

	private void addPayTransferDetail(Transfer resultTransfer) {
		
		PayTransferDetail payTransferDetail = new PayTransferDetail();
		
		payTransferDetail.setSysOrderno(resultTransfer.getOrderNo());
		payTransferDetail.setPayChannel(resultTransfer.getChannel());
		payTransferDetail.setOpenId(resultTransfer.getRecipient());
		Integer amount = resultTransfer.getAmount();
		payTransferDetail.setAmount(new BigDecimal(amount/100));
		payTransferDetail.setStatus(resultTransfer.getStatus());
		payTransferDetail.setCreateTime(currentTime);
		payTransferDetail.setUpdateTime(currentTime);
		
		int count = this.getPayTransferDetailMapper().insertSelective(payTransferDetail);
		log.info("提现申请记录插入到表中 {} 条数据.", count);
	}
	
	@Override
	public Boolean transferFinish(HttpServletRequest request) {
		Boolean blnRtn=false;
		try {
			HashMap<String,String> hashMap=Maps.newHashMap();
			String strSignatureKey="X-Pingplusplus-Signature";
			 //获取头部所有信息
	        Enumeration<String> headerNames = request.getHeaderNames();
	        while (headerNames.hasMoreElements()) {
	            String key = headerNames.nextElement().toLowerCase();
	            String value = request.getHeader(key);
	            hashMap.put(key, value);
	        }
	        String signature ="";
	        if(hashMap.containsKey(strSignatureKey.toLowerCase())){
	        		signature=hashMap.get(strSignatureKey.toLowerCase());
	        }
			// 获得 http body 内容
	        BufferedReader reader = request.getReader();
	        StringBuffer buffer = new StringBuffer();
	        String string;
	        while ((string = reader.readLine()) != null) {
	            buffer.append(string);
	        }
	        reader.close();
		    // 该数据请从 request 中获取原始 POST 请求数据
	        String webhooksRawPostData = buffer.toString();
	        blnRtn=WebVerifyUtils.verifyData(webhooksRawPostData, signature, WebVerifyUtils.getPubKey());
	     	if(blnRtn){
	     		// 解析异步通知数据
	     		Event event = Webhooks.eventParse(buffer.toString());
	     	    //支付成功
	     	    if ("charge.succeeded".equals(event.getType())) {
	     	    	blnRtn=true;         
	     	    //退款成功
	     	    } else if ("refund.succeeded".equals(event.getType())) {
	     	    	blnRtn=true;
	     	    //转账成功
	     	    } else if ("transfer.succeeded".equals(event.getType())){
	     	    	blnRtn = this.udpatePayTransferDetail(event);
	     	    } else {
	     	    	blnRtn=false;
	     	    }
	     	}
	     	return blnRtn;
		} 
		catch (Exception e) {
			log.error("PayDetailSeviceImpl.payfinish error : {}", e);
			throw new BusinessException(e);
		}
	}

	private Boolean udpatePayTransferDetail(Event event) {
		log.info("PayTransferServiceImpl.udpatePayTransferDetail param : {}", event);
		Boolean blnRtn=false;
		try {
			Object obj = Webhooks.getObject(event.toString());
			if (obj instanceof Transfer) {
				Transfer transfer = (Transfer)obj;
				String orderNo = transfer.getOrderNo();
				PayTransferDetail payTransferDetail = this.getPayTransferDetailMapper().selectByOrderNo(orderNo);
				
				// 防重
				if(payTransferDetail.getStatus()=="paid"){
					log.info("PayTransferServiceImpl.udpatePayTransferDetail repeat callback;");
					return true;
				}
				
				payTransferDetail.setThirdno(transfer.getTransaction_no());
				payTransferDetail.setStatus(transfer.getStatus());
				payTransferDetail.setTransferredTime(DateUtils.getDatetime(transfer.getTimeTransferred()));
				payTransferDetail.setUpdateTime(currentTime);
				
				int updateCount = this.getPayTransferDetailMapper().updateByPrimaryKeySelective(payTransferDetail);
				log.info("提现申请成功,更新记录 {} 条.", updateCount);
				
				// 提现完成插入到账户表数据
				this.addAccDeatailAndLedger(payTransferDetail.getOpenId(), payTransferDetail.getId(), payTransferDetail.getAmount());
				log.info("将提现数据插入到账户明细,更新账户余额 .");
				
				blnRtn = true;
			}
		} catch (Exception e) {
			log.error("提现申请回调异常.", e);
			e.printStackTrace();
		}
		return blnRtn;
	}

	private void addAccDeatailAndLedger(String openId, Long payTransferDetailId, BigDecimal amount) {
		log.info("提现信息添加到账户表中,更新余额.openId:{}, payTransferDetailId:{}, amount:{}.", openId, payTransferDetailId, amount);
		try {
			// 使用openId,查询用户信息
			UserSearch search = new UserSearch();
			search.createCriteria().andOpenIdEqualTo(openId);
			List<User> userList = this.getUserService().selectByExample(search);
			List<AccntDetail> accntDetails = new ArrayList<AccntDetail>();
			if(userList != null){
				AccntDetail accntDetail = new AccntDetail();
				User user = userList.get(0);
				
				accntDetail.setAccountId(user.getId()+"");
				accntDetail.setAccountName(user.getName());
				accntDetail.setFeetype(AccFeetypeEnum.WITHDRAWAL.getValue());
				accntDetail.setOrderId(payTransferDetailId);
				accntDetail.setOrderPrice(amount);
				accntDetail.setOrderPrice(amount);
				accntDetail.setUserType(user.getUserType());
				
				accntDetail.setCreateTime(currentTime);
				accntDetail.setUpdateTime(currentTime);
				
				log.info("提现信息添加到账户表中.参数:accntDetail:{}.", accntDetail);
				accntDetails.add(accntDetail);
				
				this.getAccntDetailService().addDetailsAndLedger(accntDetails);
			}
		} catch (Exception e) {
			log.error("提现信息添加到账户表异常.", e);
			e.printStackTrace();
		}
	}

	@Override
	public Result<Object> findAccTransfer(String transferid) {
		Result<Object> result = new Result<>(false);
		Pingpp.apiKey = StanUtils.getConstantPropertiesLoader().getProperty(PingPPConstant.PINGPP_API_AECRET_KEY);
		try {
			Transfer transfer = Transfer.retrieve(transferid);
			result.setData(transfer);
			result.setSuccess(true);
			result.setMessage("查询成功.");
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("查询异常.");
			e.printStackTrace();
		} 
		return result;
	}
	
	public PayTransferDetailMapper getPayTransferDetailMapper() {
		return this.payTransferDetailMapper;
	}

	public AccntDetailService getAccntDetailService() {
		return this.accntDetailService;
	}

	public UserService getUserService() {
		return this.UserService;
	}
	
}
*/